// 基础配置
const API_BASE_URL = '/NiDer/IndexServlet';

// 页面加载完成后执行
$(document).ready(function() {
    console.log("初始化页面")
    // 初始化页面
    initPage();
    console.log("绑定事件")
    // 绑定事件
    bindEvents();
});

function initPage() {
    console.log("检查登录状态")
    // 检查登录状态
    checkLoginStatus();
    console.log("加载版块列表")
    // 加载版块列表
    loadForums();
    console.log("加载帖子列表")
    // 加载帖子列表
    loadPosts();
    console.log("加载热门帖子")
    // 加载热门帖子
    loadHotPosts();
}

function bindEvents() {
    // 版块点击事件
    $(document).on('click', '.nav-link', function(e) {
        e.preventDefault();
        const forumId = $(this).data('forum-id');
        const forumName = $(this).text();
        loadPosts(forumId);
        $('#currentForum').text(forumName);

        // 高亮当前版块
        $('.nav-link').removeClass('active');
        $(this).addClass('active');
    });

    // 标签切换事件
    $(document).on('click', '.tab-btn', function() {
        const type = $(this).data('type');
        $('.tab-btn').removeClass('active');
        $(this).addClass('active');
        loadPosts(null, type);
    });

    // 加载更多按钮
    $(document).on('click', '#loadMore', function() {
        loadMorePosts();
    });

    // 搜索功能
    $(document).on('click', '.navbar-search button', function() {
        const keyword = $('.navbar-search input').val().trim();
        if (keyword !=null) {
            searchPosts(keyword);
        }else if(keyword ==null) {
            getPosts();
        }
    });

    // 回车搜索
    $(document).on('keypress', '.navbar-search input', function(e) {
        if (e.which === 13) {
            const keyword = $(this).val().trim();
            if (keyword) {
                searchPosts(keyword);
            }
        }
    });

    // 删除帖子事件
    $(document).on('click', '.delete-post', function() {
        const postId = $(this).data('post-id');
        if (confirm('确定要删除这个帖子吗？')) {
            deletePost(postId);
        }
    });

    // 发帖按钮点击事件
    $(document).on('click', '#createPostBtn', function() {
        showPostEditor();
    });
}

// 添加显示发帖编辑器的函数
function showPostEditor() {
    const editorHtml = `
        <div class="post-editor">
            <h4>发表新帖</h4>
            <div class="form-group">
                <label for="postTitle">标题</label>
                <input type="text" id="postTitle" class="form-control" placeholder="请输入标题">
            </div>
            <div class="form-group">
                <label for="postForum">选择版块</label>
                <select id="postForum" class="form-control">
                    <!-- 版块选项将通过JS动态加载 -->
                </select>
            </div>
            <div class="form-group">
                <label for="postContent">内容</label>
                <textarea id="postContent" class="form-control" rows="10" placeholder="请输入内容"></textarea>
            </div>
            <div class="editor-actions">
                <button class="btn btn-primary" id="submitPostBtn">提交</button>
                <button class="btn btn-secondary" id="cancelPostBtn">取消</button>
            </div>
        </div>
    `;

    $('#postList').html(editorHtml);
    $('#currentForum').text('发表新帖');

    // 加载版块选项
    loadForumOptions();

    // 绑定提交和取消按钮事件
    $(document).on('click', '#submitPostBtn', submitPost);
    $(document).on('click', '#cancelPostBtn', function() {
        loadPosts();
        $('#currentForum').text('最新帖子');
    });
}

// 加载版块选项
function loadForumOptions() {
    $.ajax({
        url: API_BASE_URL,
        type: 'POST',
        data: { action: 'getForums' },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                const forums = response.data || [];
                let optionsHtml = '<option value="">请选择版块</option>';

                forums.forEach(forum => {
                    optionsHtml += `<option value="${forum.forumId}">${forum.name}</option>`;
                });

                $('#postForum').html(optionsHtml);
            }
        }
    });
}

// 提交帖子
function submitPost() {
    console.log()

    const userId = document.cookie.split('=')[1];
    if (!userId) {
        alert('请先登录！');
        window.location.href = '../pages/login.html'; // 跳转到登录页
        return;
    }

    const title = $('#postTitle').val().trim();
    const content = $('#postContent').val().trim();
    const forumId = $('#postForum').val();

    if (!title || !content || !forumId) {
        alert('请填写完整信息！');
        return;
    }

    console.log(userId)
    $.ajax({
        url: '/NiDer/PostServlet',
        type: 'POST',
        data: {
            action: 'createPost',
            title: title,
            content: content,
            userId: userId, // 直接使用获取到的用户ID
            forumId: forumId
        },
        success: function(response) {
            if (response.success) {
                alert('发帖成功！');
                loadPosts();
            }
        }
    });
}


//

function checkLoginStatus() {
    $.ajax({
        url: API_BASE_URL,
        type: 'POST',
        data: { action: 'checkLogin' },
        dataType: 'json',
        success: function(response) {
            console.log(response)
            if (response.success) {
                renderUserInfo(response.user);
            } else {
                renderLoginButtons();
            }
        },
        error: function(xhr, status, error) {
            console.error('检查登录状态失败:', error);
            renderLoginButtons();
        }
    });
}

function renderUserInfo(user) {
    // 用户信息卡片
    $('#userCard').html(`
        <div class="card-body">
            <div class="user-info">
                <div class="user-name">${user.username}</div>
                <div class="user-email">${user.email}</div>
                <div class="user-stats">
                    <div class="stat-item">
                        <div class="stat-value">${user.postCount || 0}</div>
                        <div class="stat-label">帖子</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${user.commentCount || 0}</div>
                        <div class="stat-label">评论</div>
                    </div>
                </div>
                <div class="user-actions">
<!--                    <button class="user-btn btn-profile" onclick="location.href='profile.html'">个人中心</button>-->
                    <button class="user-btn btn-logout" id="logoutBtn">退出登录</button>
                </div>
            </div>
        </div>
    `);

    // 顶部用户操作区
    $('#userActions').html(`
        <div class="user-dropdown">
            <a href="#" class="dropdown-toggle">
                <span>${user.username}</span>
            </a>
            <div class="dropdown-menu">
<!--                <a class="dropdown-item" href="profile.html">个人中心</a>-->
<!--                <a class="dropdown-item" href="settings.html">设置</a>-->
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" href="#" id="logoutBtn">退出登录</a>
            </div>
        </div>
    `);

    // 退出登录事件
    $(document).on('click', '#logoutBtn', function() {
        $.ajax({
            url: API_BASE_URL,
            type: 'POST',
            data: { action: 'logout' },
            success: function() {
                window.location.href="../pages/login.html";
            },
            error: function(xhr, status, error) {
                console.error('退出登录失败:', error);
            }
        });
    });
}

function renderLoginButtons(user) {
    $('#userActions').html(`
        <a href="../pages/login.html" class="btn btn-outline-light btn-sm me-2">登录</a>
        <a href="../pages/register.html" class="btn btn-light btn-sm">注册</a>
    `);

    $('#userCard').html(`
        <div class="card-body text-center">
            <div class="user-email">${user.email}</div>
            <div class="user-name">${user}</div>
        </div>
    `);
}

function loadForums() {
    $.ajax({
        url: API_BASE_URL,
        type: 'POST',
        data: { action: 'getForums' },
        dataType: 'json',
        success: function(response) {
            // 检查请求是否成功
            if (response.success) {
                // 从 response.data 获取论坛列表
                const forums = response.data || [];

                let forumListHtml = '';
                forums.forEach(forum => {
                    forumListHtml += `
                        <li class="nav-item">
                            <a href="#" class="nav-link" data-forum-id="${forum.forumId}">
                                ${forum.name}
                            </a>
                        </li>
                    `;
                });
                $('#forumList').html(forumListHtml);
            } else {
                console.error('加载失败:', response.message);
                $('#forumList').html('<li class="text-muted">加载失败: ' + (response.message || '未知错误') + '</li>');
            }
        },
        error: function(xhr, status, error) {
            console.error('请求失败:', error);
            $('#forumList').html('<li class="text-muted">网络请求失败</li>');
        }
    });
}

// 修改 loadPosts 函数
function loadPosts(forumId = null, type = 'new', loadMore = false) {

    console.log(1)
    let data = { action: 'getPosts', type: type };

    if (forumId) {
        data.forumId = forumId;
    }

    if (loadMore) {
        const currentPage = $('#postList').data('current-page') || 1;
        data.page = currentPage + 1;
    } else {
        data.page = 1;
    }

    $.ajax({
        url: API_BASE_URL,
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(response) {
            // 修改这里：确保获取的是数组数据
            const postsData = response.success ? response.data : [];
            console.log(postsData)
            renderPosts(postsData);

            // 存储当前页数
            $('#postList').data('current-page', data.page);

            // 如果还有更多数据，显示加载更多按钮
            if (response.hasMore) {
                $('#loadMore').show();
            } else {
                $('#loadMore').hide();
            }
        },
        error: function(xhr, status, error) {
            console.error('加载帖子列表失败:', error);
            $('#postList').html('<div class="alert alert-danger">加载帖子失败</div>');
        }
    });
}

function renderPosts(posts) {
    if (posts.data!=undefined||posts.data!=null){
         posts = Array.isArray(posts.data)?posts.data:[posts.data]
     }
    // 确保 posts 是数组
    if (!Array.isArray(posts)) {
        console.warn('posts 不是数组:', posts);
        posts = [];
    }

    let postsHtml = '';

    if (posts.length === 0) {
        postsHtml = '<div class="empty-message">暂无帖子</div>';
    } else {
        posts.forEach(post => {
            // 确保 post 对象存在必要属性
            const safePost = {
                postId: post.postId || 0,
                title: post.title || '无标题',
                content: post.content || '',
                username: post.username || '匿名用户',
                createdAt: post.createdAt || new Date().toISOString(),
                views: post.views || 0,
                commentCount: post.commentCount || 0,
                likeCount: post.likeCount || 0
            };

            postsHtml += `
                <div class="post-item" data-post-id="${safePost.postId}">
                    <div class="post-title">${safePost.title}</div>
                    <div class="post-meta">
                        <span>作者: ${safePost.username}</span>
                        <span>时间: ${formatDate(safePost.createdAt)}</span>
                        <span>浏览: ${safePost.views}</span>
                    </div>
                    <div class="post-content-preview">
                        ${safePost.content.substring(0, 150)}...
                    </div>
                    <div class="post-stats">
                        <div class="post-stat">评论: ${safePost.commentCount}</div>
                        <div class="post-stat">点赞: ${safePost.likeCount}</div>
                    </div>
                </div>
            `;
        });
    }

    if ($('#postList').data('current-page') > 1) {
        $('#postList').append(postsHtml);
    } else {
        $('#postList').html(postsHtml);
    }
}

// 添加删除帖子的函数
function deletePost(postId) {
    $.ajax({
        url: '/NiDer/DeleteServlet',
        type: 'POST',
        data: { postId: postId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                alert('删除成功');
                // 刷新帖子列表
                loadPosts();
            } else {
                alert(response.message || '删除失败');
            }
        },
        error: function(xhr, status, error) {
            console.error('删除帖子失败:', error);
            alert('删除失败，请稍后再试');
        }
    });
}

// 同样修改 loadHotPosts 和 renderHotPosts 函数
function loadHotPosts() {
    $.ajax({
        url: API_BASE_URL,
        type: 'POST',
        data: { action: 'getHotPosts' },
        dataType: 'json',
        success: function(response) {
            const hotPostsData = response.success ? response.data : [];
            renderHotPosts(hotPostsData);
        },
        error: function(xhr, status, error) {
            console.error('加载热门帖子失败:', error);
            $('#hotPosts').html('<li class="text-muted">加载热门帖子失败</li>');
        }
    });
}

function renderHotPosts(posts) {
    if (!Array.isArray(posts)) {
        posts = [];
    }

    let postsHtml = '';

    if (posts.length === 0) {
        postsHtml = '<li class="text-muted">暂无热门帖子</li>';
    } else {
        posts.forEach(post => {
            const safePost = {
                postId: post.postId || 0,
                title: post.title || '无标题',
                views: post.views || 0
            };

            postsHtml += `
                <li class="hot-post-item">
                    <a href="post.html?id=${safePost.postId}" class="hot-post-title">${safePost.title}</a>
                    <div class="hot-post-meta">
                        <span>浏览: ${safePost.views}</span>
                    </div>
                </li>
            `;
        });
    }

    $('#hotPosts').html(postsHtml);
}
function loadMorePosts() {
    const currentForum = $('.nav-link.active').data('forum-id') || null;
    const currentTab = $('.tab-btn.active').data('type');
    loadPosts(currentForum, currentTab, true);
}

function searchPosts(keyword) {
    $.ajax({
        url: API_BASE_URL,
        type: 'POST',
        data: { action: 'searchPosts', keyword: keyword },
        dataType: 'json',
        success: function(response) {
            renderPosts(response);
            $('#currentForum').text('搜索结果');
            $('.nav-link').removeClass('active');
        },
        error: function(xhr, status, error) {
            console.error('搜索帖子失败:', error);
            $('#postList').html('<div class="alert alert-danger">搜索失败</div>');
        }
    });
}

function formatDate(dateString) {
    if (!dateString) return '';

    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 获取点赞数量
function getLikeCount(postId, callback) {
    $.ajax({
        url: '/NiDer/LikeServlet',
        type: 'POST',
        data: { action: 'getLikeCount', postId: postId },
        dataType: 'json',
        success: function(response) {
            if (response.success && typeof callback === 'function') {
                callback(response.data);
            } else {
                console.error('获取点赞数量失败:', response.message);
                callback(0);
            }
        },
        error: function(xhr, status, error) {
            console.error('请求点赞数量失败:', error);
            callback(0);
        }
    });
}

// 获取评论数量
function getCommentCount(postId, callback) {
    $.ajax({
        url: '/NiDer/CommentServlet',
        type: 'POST',
        data: { action: 'getCommentCount', postId: postId },
        dataType: 'json',
        success: function(response) {
            if (response.success && typeof callback === 'function') {
                callback(response.data);
            } else {
                console.error('获取评论数量失败:', response.message);
                callback(0);
            }
        },
        error: function(xhr, status, error) {
            console.error('请求评论数量失败:', error);
            callback(0);
        }
    });
}

function renderPosts(posts) {
    if (posts.data!=undefined||posts.data!=null){
        posts = Array.isArray(posts.data)?posts.data:[posts.data]
    }
    // 确保 posts 是数组
    if (!Array.isArray(posts)) {
        console.warn('posts 不是数组:', posts);
        posts = [];
    }

    let postsHtml = '';

    if (posts.length === 0) {
        postsHtml = '<div class="empty-message">暂无帖子</div>';
    } else {
        posts.forEach(post => {
            // 确保 post 对象存在必要属性
            const safePost = {
                postId: post.postId || 0,
                title: post.title || '无标题',
                content: post.content || '',
                username: post.username || '匿名用户',
                createdAt: post.createdAt || new Date().toISOString(),
                views: post.views || 0,
                commentCount: post.commentCount || 0,
                likeCount: post.likeCount || 0
            };

            // 获取评论数和点赞数
            getCommentCount(safePost.postId, function(commentCount) {
                getLikeCount(safePost.postId, function(likeCount) {
                    postsHtml += `
                        <div class="post-item" data-post-id="${safePost.postId}">
                            <div class="post-title">${safePost.title}</div>
                            <div class="post-meta">
                                <span>作者: ${safePost.username}</span>
                                <span>时间: ${formatDate(safePost.createdAt)}</span>
                                <span>浏览: ${safePost.views}</span>
                            </div>
                            <div class="post-content-preview">
                                ${safePost.content.substring(0, 150)}...
                            </div>
                            <div class="post-stats">
                                <div class="post-stat">评论: ${commentCount}</div>
                                <div class="post-stat">点赞: ${likeCount}</div>
                        <a href="javascript:void(0);" class="delete-post" data-post-id="${safePost.postId}">删除</a>                                                                            
                                
                            </div>
                        </div>
                    `;

                    // 如果是第一页，直接替换内容；否则追加内容
                    if ($('#postList').data('current-page') > 1) {
                        $('#postList').append(postsHtml);
                    } else {
                        $('#postList').html(postsHtml);
                    }
                });
            });
        });
    }
}
